/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trocabi.service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.NumberFormatter;
import trocabi.DAO.DAOArticle;
import trocabi.DAO.DAODepositaire;
import trocabi.Parameters;
import trocabi.Socle.TechnicalException;
import trocabi.model.Article;
import trocabi.model.Article.Etat;
import trocabi.model.Depositaire;

/**
 *
 * @author philippe
 */
public class ArticleServices {
     private DAOArticle               daoArticle = DAOArticle.getInstance();
     private SimpleDateFormat         dateFormat = new SimpleDateFormat(Parameters.FORMAT_DATE);
     private NumberFormatter          displayFormatter = new NumberFormatter(new DecimalFormat(Parameters.FORMAT_PRICE));
    
    
     public void create(Article article) throws TechnicalException {
        article.setId(daoArticle.insert(article));
     }
     
     public void update(Article article) throws TechnicalException {
        daoArticle.update(article);
     }
     
     public Article get(long id) throws TechnicalException  {
         return daoArticle.get(id);
     }
      /*
      * Chercher un article a partir de son code codeBarre
      */
     public ArrayList<Article> chercherArticle(String sCodeBarre) throws TechnicalException {
          // vérification champ "Code Barre"
         /*
         if (formatageIntPositif(CODE_BARRE, sCodeBarre) == -1) {
         fenetreExterne(ERREUR, "Le champ \"Code barre\" ne respecte pas le format de donnée attendu.\nCi-dessous le format attendu :\n     - Code Barre : ##########\n\nLes '#' correspondent à un chiffre (0 à 9)");
         return;
         }
         * */
        // Sélection en BDD par code barre
        ArrayList<String[]> listConditions_Article = new <String[]> ArrayList();
        String[] stabConditions_Articles;
        // Condition sur le numéro d'article
        stabConditions_Articles = new String[4];
        stabConditions_Articles[DAOArticle.iID_DB] = DAOArticle.FD_ID;
        stabConditions_Articles[DAOArticle.iVALEUR] = sCodeBarre;
        stabConditions_Articles[DAOArticle.iMODE_COMPARAISON] = DAOArticle.sEGAL_STRICT;
        stabConditions_Articles[DAOArticle.iMODE_TRIE] = null;
        listConditions_Article.add(stabConditions_Articles);
        return daoArticle.listSelect(listConditions_Article, null, DAOArticle.iNO_LIMIT);
     }
     
    public void changeState(Article article, Etat etat) throws TechnicalException { 
        Article tmpArticle=(Article) article.clone();
        tmpArticle.setSituation(etat); 
        tmpArticle.setDateChangementEtat(new Date());
        daoArticle.update(tmpArticle);    // update sgbd
        article.setSituation(etat);    // update article if success (no exception)
    }
    
    public ArrayList<Article> searchUntilDateDepot(Depositaire depositaire, Date dateDepot) throws TechnicalException {
        String query;
        
        if (dateDepot==null) {  // Sélection des trois dernières date de dépôt si le champ date est vide
            query=String.format("SELECT DISTINCT (DATE_DEPOT) FROM ARTICLE WHERE NUMERO_DEPOSITAIRE = %d ORDER BY DATE_DEPOT DESC  LIMIT 0,3",
                     depositaire.getId());
        }
        else {
            query=String.format("SELECT * FROM ARTICLE WHERE NUMERO_DEPOSITAIRE = %d AND DATE_DEPOT >= '2010-10-10'",
                    depositaire.getId(),
                    new java.sql.Date(dateDepot.getTime()).toString()); // conversion date java -> sql
        }
        return daoArticle.searchArticles(query);
    }
    
    /*
      * Chercher un article a partir de son code codeBarre
      */
     public ArrayList<Article> searchArticleByStatus(Depositaire depositaire, Article.Etat status) throws TechnicalException {
        String query=String.format("SELECT * FROM %s WHERE %s = %d AND %s = '%s'",
                    DAOArticle.TB_ARTICLE, 
                    DAOArticle.FD_ID_DEPOSITAIRE, depositaire.getId(), 
                    DAOArticle.FD_STATUS, Article.etatToCode(status));
        return daoArticle.searchArticles(query);
     }
     
     public static String idToString(Article article) {
         return String.format(Parameters.FORMAT_ID_ARTICLE,article.getId());
     }
     
     public String dateToString(Date date) {
         return dateFormat.format(date);
     }
     
    public String priceToString(double price) {
        String result = "";
        
        try {
            result = displayFormatter.valueToString((Double) price);
        } catch (ParseException ex) {
            Logger.getLogger(ArticleServices.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
}